<template>
  <div style="height: 100%">
    <AHMF
      :asideWidth="300"
      :rightTitleShow="false"
      :AShow="false"
      :FShow="true"
    >
      <template #header>
        <topSearcher
          :searchOptions="searchOptions"
          @onQuery="onQuery"
          @onReset="onReset"
        ></topSearcher>
      </template>
      <template #main>
        <div style="margin-bottom: 10px; display: flex; height: 100%">
          <el-tabs v-model="activeSceneId" type="card" @tab-click="tabClick">
            <el-tab-pane
              :label="item.name"
              :name="item.value"
              v-for="item in sceneArr"
              :key="item.value"
            >
              <div class="item-container">
                <div v-for="n in tableData" :key="n.id" class="item-main">
                  <div class="item" @click="itemClick(n)">
                    <!-- <div class="status">{{ "状态" }}</div> -->
                    <div @click.stop>
                      <el-dropdown trigger="click">
                        <el-button type="text">
                          <i style="font-size: 20px" class="el-icon-more"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item
                            @click.native.stop="add_editFn(n, 'view')"
                            >详情</el-dropdown-item
                          >
                          <el-dropdown-item
                            @click.native.stop="add_editFn(n, 'edit')"
                            >编辑</el-dropdown-item
                          >

                          <el-dropdown-item @click.native.stop="delFn(n)"
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>

                    <div class="field" data-label="项目编码:">
                      {{ n.projectCode }}
                    </div>
                    <div class="field" data-label="评估次数:">
                      <span style="color: #3c9cff">{{ n.evalNum }}</span>
                      <span style="margin-left: 10px">次</span>
                    </div>
                    <div class="field" data-label="创建时间:">
                      {{ n.crTime }}
                    </div>
                  </div>
                  <div style="font-weight: bold">{{ n.projectName }}</div>
                </div>
                <div class="item-main">
                  <div class="item additem" @click.stop="add_editFn('', 'add')">
                    <i style="font-size: 40px" class="el-icon-plus"></i>
                  </div>
                  <div style="font-weight: bold; color: #3c9cff">添加场景</div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <div class="flex">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.currPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
          >
          </el-pagination>
        </div>
      </template>
    </AHMF>
    <Edialog
      :outershow="addDialogShow"
      :title="dialogTitle"
      width="50%"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="dialogTitle !== '详情' ? true : false"
      :internal="true"
      ref="dialogRef"
    >
      <el-form
        v-if="dialogTitle == '新增' || dialogTitle == '编辑'"
        :model="addForm"
        label-width="80px"
        ref="addFormRef"
        :rules="addFormRules"
      >
        <el-form-item label="项目场景">
          {{ addForm.sceneName }}
        </el-form-item>
        <el-form-item label="项目编码" prop="projectCode">
          <el-input v-model="addForm.projectCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="addForm.projectName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addForm.remark"
            autocomplete="off"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div v-else>
        <el-descriptions :column="2">
          <el-descriptions-item label="项目场景">{{
            addForm.sceneName
          }}</el-descriptions-item>
          <el-descriptions-item label="项目编码">{{
            detailForm.projectCode
          }}</el-descriptions-item>
          <el-descriptions-item label="项目名称">{{
            detailForm.projectName
          }}</el-descriptions-item>
          <el-descriptions-item label="项目评估次数">
            <!-- <el-tag size="small">{{ detailForm.evalCount || 0 }}</el-tag> -->
            {{ detailForm.evalCount || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            detailForm.crTime
          }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{
            detailForm.remark
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </Edialog>
    <!-- 模板编辑 -->
    <template_edit
      ref="template_edit"
      @refreshFn="getTableData"
    ></template_edit>
  </div>
</template>
<script>
import topSearcher from "@/components/topSearcher/topSearcher.vue";
import AHMF from "@/components/topSearcher/AHMF.vue";
import ETable from "@/components/ETable";
import Edialog from "@/components/Edialog";

import template_edit from "./components/template_edit.vue";
import {
  putProjectInfoApi,
  postProjectInfoApi,
  deleteProjectInfoByIds,
  ProjectInfoApi,
  ProjectInfoByIdApi,
  ProjectInfoCopyByIdApi,
} from "@/api/projectManage";
import {
  putSceneInfoApi,
  postSceneInfoApi,
  deleteSceneInfoByIds,
  SceneInfoApi,
  SceneInfoByIdApi,
  SceneInfoCopyByIdApi,
  putSceneTemplateApi,
  postSceneTemplateApi,
  SceneTemplateCopyByIdApi,
  deleteSceneTemplateByIds,
  SceneTemplateApi,
  SceneTemplateByIdApi,
} from "@/api/sceneManage";
import { getToken } from "@/utils/auth";
export default {
  components: {
    ETable,
    Edialog,
    AHMF,
    topSearcher,

    template_edit,
  },

  data() {
    return {
      activeSceneId: "",
      dialogTitle: "新增",

      sceneArr: [],
      addFormRules: {
        projectCode: [
          { required: true, message: "请输入项目编码", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        sceneId: [{ required: true, message: "请选择场景", trigger: "blur" }],
      },
      addForm: {
        sceneName: "",
        sceneId: "",
        projectCode: "",
        projectName: "",
        remark: "",
      },
      // 新增弹窗
      addDialogShow: false,
      defaultProps: {
        children: "children",
        label: "label",
      },

      // 搜索字段
      searchOptions: [
        {
          type: "input",
          label: "项目名称",
          key: "projectName",
          value: "",
        },
      ],
      tableHeight: "随便设置的字符串，只要是字符串，表格高度就会受控于外部样式",
      searchForm: {},
      tableData: [],
      tableLoading: false,
      pageInfo: {
        currPage: 1,
        pageSize: 10,
        total: 0,
      },
      batchData: [],
      batchDataIds: [],
      spreadsheetData: [],
      detailForm: {},
      type: "",
    };
  },
  async created() {
    await this.getSceneTabs();
    this.getTableData();
  },
  methods: {
    // 获取表格数据
    async getTableData() {
      if (this.activeSceneId == 0) {
        return;
      }
      this.tableLoading = true;
      console.log("查询", this.activeSceneId);
      // 没有排序条件
      let obj = {
        currPage: this.pageInfo.currPage,
        pageSize: this.pageInfo.pageSize,
        sceneId: this.activeSceneId,
        ...this.searchForm,
      };
      if (obj.sortStr == "") {
        delete obj.sortStr;
      } else {
        // 有排序条件
        obj.sortStr = this.searchForm.sortStr;
      }

      let res = await ProjectInfoApi(obj);
      if (res.data && res.data.bdata.total > 0) {
        this.tableData = res.data.bdata.gdata;
        this.pageInfo.total = res.data.bdata.total;
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.tableLoading = false;
    },
    tabClick(data) {
      console.log(data);
      this.pageInfo.currPage = 1;
      this.addForm.sceneId = data.name;
      this.addForm.sceneName = data.label;

      this.getTableData();
    },
    async getSceneTabs() {
      this.sceneArr = [];
      let res = await SceneInfoApi({
        currPage: 1,
        pageSize: 9999,
      });
      if (res.data && res.data.bcode == 0) {
        if (res.data.bdata && res.data.bdata.gdata.length > 0) {
          res.data.bdata.gdata.forEach((item) => {
            this.sceneArr.push({
              name: item.sceneName.toString(),
              value: item.id.toString(),
            });
          });
          this.activeSceneId = this.sceneArr[0].value;
          this.addForm.sceneId = this.sceneArr[0].value;
          this.addForm.sceneName = this.sceneArr[0].name;

          console.log("this.sceneArr[0]", this.sceneArr[0]);
        } else {
          this.activeSceneId = "";
          this.sceneArr = [];
        }
      }
      console.log("场景tabs", res);
    },
    // 新增/编辑
    add_editFn(scope, type) {
      this.type = type;
      this.addDialogShow = true;
      if (type == "edit") {
        this.$nextTick(() => {
          this.addForm.projectCode = scope.projectCode;
          this.addForm.projectName = scope.projectName;
          this.addForm.remark = scope.remark;
        });
        this.dialogTitle = "编辑";
      } else if (type == "add") {
        this.dialogTitle = "新增";
      } else {
        this.dialogTitle = "详情";
        ProjectInfoByIdApi(scope.id).then((res) => {
          if (res.data && res.data.bcode == 0) {
            this.detailForm = res.data.bdata;
          }
        });
      }
      console.log("scope", scope);
      this.addForm.sceneId = this.activeSceneId;
    },
    //dialog保存
    saveFn() {
      this.$nextTick(() => {
        this.$refs.addFormRef.validate((valid) => {
          if (valid) {
            if (this.type == "edit") {
              postProjectInfoApi(this.addForm).then((res) => {
                if (res.data && res.data.bcode == 0) {
                  this.$message.success("保存成功");
                  this.addDialogShow = false;
                  this.getTableData();
                }
              });
            } else {
              putProjectInfoApi(this.addForm).then((res) => {
                if (res.data && res.data.bcode == 0) {
                  this.$message.success("保存成功");
                  this.addDialogShow = false;
                  this.getTableData();
                }
              });
            }
          }
        });
      });
    },
    //dialog关闭
    closeFn() {
      if (this.$refs.addFormRef) {
        this.$refs.addFormRef.resetFields();
      }

      this.addDialogShow = false;
    },
    itemClick(data) {
      this.$refs.template_edit.openFn(data);
    },
    viewFn(scope) {
      this.$refs.template_edit.openFn(scope.row);
    },
    //模板配置
    tempConfigFn(scope) {
      console.log(this.$refs.template_config);
      this.$refs.template_config.manufacturerOpen();
    },

    async delFn(scope) {
      let t = await this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let res = await deleteProjectInfoByIds(scope.id);
        if (res.data && res.data.bcode == 0) {
          // // 页数大于一页并且当前页只有一条数据，删除后页数-1
          // if (
          //   this.pageInfo.total % this.pageInfo.pageSize === 1 &&
          //   this.pageInfo.currPage > 1
          // ) {
          //   this.pageInfo.currPage -= 1;
          // }
          this.$message.success(res.data.bmsg || "删除成功");
          this.getTableData();
        }
      }
    },
    async sortFun(obj) {
      console.log("---", obj);
      this.pageInfo.sortList = obj;
      if (obj == "") {
        return this.getTableData();
      }
    },

    onReset(searchForm) {
      console.log("重置", searchForm);
      // this.searchForm = searchForm;
      this.pageInfo.currPage = 1;
      this.onQuery(searchForm);
    },
    onQuery(searchForm) {
      console.log("查询", searchForm);
      this.searchForm = searchForm;
      this.getTableData();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageInfo.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageInfo.currPage = val;
      this.getTableData();
    },
    onSubmit() {
      console.log("submit!");
    },
    handleNodeClick(data) {
      console.log(data);
      // this.spreadsheetData = JSON.parse(localStorage.getItem("loadData"));
    },
    handleClick(row) {
      console.log(row);
    },
    //树节点筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>
<style lang="scss" scoped>
.item-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  justify-content: flex-start;
  padding: 0 10px;
}
.item {
  width: 100%;
  height: 120px;
  border: 1px solid #ccc;
  margin: 10px;
  padding: 10px 10px 10px 10px;
  position: relative;
  text-align: left; /* 使文字左对齐 */
  border-radius: 8px; /* 添加弧度 */
  display: flex;
  flex-direction: column;
  cursor: pointer;
}
.item-main {
  margin-bottom: 8px;
  width: 18%; /* 一行5个，考虑到margin和padding，这里设置为18% */
  margin-right: 30px;
}
.status {
  position: absolute;
  top: -25px; /* 调整位置，使其出格 */
  left: -15px; /* 调整位置，使其出格 */
  background-color: #007bff;
  color: white;
  font-size: 14px;
  padding: 3px 6px;
  border-radius: 5px; /* 添加圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 添加阴影 */
  transform: rotate(-45deg); /* 逆时针旋转45度 */
  transform-origin: bottom right; /* 设置旋转的基点 */
}
.el-dropdown {
  position: absolute;
  top: 0px;
  right: 10px;
  height: 30px;
}
.dropdown-button {
  position: absolute;
  top: 10px;
  right: 10px;
  color: #333;
}
.field {
  margin: 8px 0;
}
.field::before {
  content: attr(data-label);
  font-weight: bold; /* 加粗字体 */
  margin-right: 10px; /* 添加右边距 */
}
.additem {
  justify-content: center;
  align-items: center;
}
.el-tabs {
  width: 100%;
  height: 100%;
}
::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  color: #fff !important;
  background: #409eff !important;
}
::v-deep .el-descriptions-item__label:not(.is-bordered-label) {
  font-weight: bold;
}
</style>
